package qf.sail.filter;


import com.alibaba.fastjson.JSON;
import qf.sail.contents.CodeMsg;
import qf.sail.contents.Contents;
import qf.sail.entity.Account;
import qf.sail.vo.ResultVO;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Account account = (Account) req.getSession().getAttribute("account");
        boolean notFilter = Arrays.stream(Contents.LOGIN_FILTER_URL).anyMatch(item -> req.getRequestURI().contains(item));
        if(notFilter){
            filterChain.doFilter(req, resp);
            return;
        }
        if(account == null){
            this.repError(resp,CodeMsg.NO_LOGIN);
            return;
        }
        filterChain.doFilter(req, resp);
    }

    protected void repError(HttpServletResponse resp, CodeMsg codeMsg){
        ResultVO resultVO = new ResultVO();
        resultVO.setMsg(codeMsg.getMsg());
        resultVO.setStatus(codeMsg.getCode());
        try {
            resp.getWriter().write(JSON.toJSONString(resultVO));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
